package example.SFTP.JSCHexample;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class JSCHDownloadMngr {
	public String readFileUsingJSCH(String ftpHostname,String ftpUsername,String ftpPassword, String fileName) throws JSchException, SftpException, IOException{
		JSch jsch = new JSch();
        Session session = null;

        session = jsch.getSession(ftpUsername, ftpHostname, 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(ftpPassword);
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        sftpChannel.get(fileName, "localfile.txt");
        sftpChannel.exit();
        session.disconnect();
        
        File file = new File("localfile.txt");
        
        FileInputStream stream = new FileInputStream(file);

		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
				fc.size());
		/* Instead of using default, pass in a decoder. */
		return Charset.defaultCharset().decode(bb).toString();
       
	}
}
